<template>
  <div>
    <h3>发表评论</h3>
    <hr />
    <textarea placeholder="请输入你想要发表的内容，120字以内" maxlength="120" v-model="Postcomment"></textarea>
    <mt-button type="primary" size="large" @click="addComment">发表评论</mt-button>
    <div class="cms-list">
      <div class="cms-item" v-for="(item,i) in commentsList" :key="item.add_time">
        <div
          class="cms-title"
        >第{{i+1}}楼&nbsp;&nbsp;用户：{{item.user_name}} &nbsp;&nbsp;发表时间：{{item.add_time | dataFormat}}</div>
        <div class="cms-body">{{item.content === 'undefined' ? '此用户很懒没有发表评论' : item.content}}</div>
      </div>
    </div>
    <mt-button type="danger" size="large" plain @click="getMore">加载更多</mt-button>
  </div>
</template>

<script>
import { Toast } from "mint-ui";
export default {
  data() {
    return {
      commentsList: [],
      pageindex: 1,
      Postcomment: ""
    };
  },
  created() {
    this.getComments();
  },
  methods: {
    getComments() {
      this.$http
        .get(
          "http://www.liulongbin.top:3005/api/getcomments/ " +
            this.id +
            "?pageindex=" +
            this.pageindex
        )
        .then(result => {
          if (result.body.status === 0) {
            this.commentsList = this.commentsList.concat(result.body.message);
          } else {
            Toast("加载评论失败");
          }
        });
    },
    getMore() {
      this.pageindex++;
      this.getComments();
    },
    addComment() {
      if (this.Postcomment.trim().length == 0) {
        return Toast("评论内容不能为空");
      }
      this.$http
        .post(
          "http://www.liulongbin.top:3005/api/postcomment/" +
            this.$route.params.id,
          {
            content: this.Postcomment.trim()
          }
        )
        .then(result => {
          if (result.body.status === 0) {
            var cmt = {
              user_name: "匿名用户",
              add_time: Date.now(),
              content: this.Postcomment.trim()
            };
            this.commentsList.unshift(cmt);
            this.Postcomment = "";
          }
        });
    }
  },
  props: ["id"]
};
</script>

<style lang="scss" scoped>
textarea {
  margin: 0;
  height: 85px;
}
.cms-list {
  margin: 10px 0;
  .cms-item {
    .cms-title {
      background-color: gray;
      font-size: 14px;
    }
    .cms-body {
      font-size: 15px;
    }
  }
}
</style>